import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Form, Input, Alert } from "antd";
import { $register } from "../../apis/userApi";
import styles from "./register.module.scss";

export default function Login() {
  const navigate = useNavigate();
  const [show, setShow] = useState(false);

  const reg = /[0-9]{3,16}/;
  // 提交表单
  const onFinish = async (values) => {
    if (reg.test(values.newLoginPwd)) {
      await $register(values).then((res) => {
        setShow(true);
        setTimeout(() => {
          navigate("/login");
        }, 1000);
      });
      return;
    }
    alert("密码为3-16位的数字");
  };

  const [form] = Form.useForm();

  return (
    <div className={styles.login}>
      <div className={styles.content}>
        <h2>注册账号</h2>
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 600,
          }}
          initialValues={{
            loginId: "",
            loginPwd: "",
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="新账号"
            name="newLoginId"
            rules={[
              {
                required: true,
                message: "请输入新账号!",
              },
            ]}
          >
            <Input placeholder="后台数据原因,建议使用 new 为注册账号" />
          </Form.Item>

          <Form.Item
            label="密码"
            name="newLoginPwd"
            rules={[
              {
                required: true,
                message: "请输入密码",
              },
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 4,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              注册
            </Button>

            <Button
              onClick={() => {
                form.resetFields();
              }}
              style={{ marginLeft: "10px" }}
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className={styles.notice}>
        {show ? (
          <Alert
            message="Success Tips"
            description="注册成功，请登录"
            type="success"
            showIcon
          />
        ) : (
          ""
        )}
      </div>
    </div>
  );
}
